<template>
   <!-- 选择岗位弹窗 -->
   <el-dialog title="选择岗位" v-model="visible" width="1200px" top="5vh" append-to-body @close="onCloseDialog">

      <el-row :gutter="20">
         <!-- 部门 -->
         <el-col :span="6">
            <el-input clearable v-model="deptNameSearch" placeholder="请输入部门名称">
               <template #prefix>
                  <el-icon class="el-input__icon">
                     <search />
                  </el-icon>
               </template>
            </el-input>


            <!-- 树形结构 -->
            <el-tree  :default-expanded-keys="expandedKeys"  node-key="id" ref="deptTreeRef" :filter-node-method="filterNode" accordion  highlight-current
               :data="deptArr" style="margin-top: 10px;" :props="{ label: 'label', children: 'children',id:'id' }"
               @node-click="onClickNode"></el-tree>

         </el-col>

         <!-- 岗位列表 -->
         <el-col :span="18">
            <el-form :model="queryParams" ref="queryRef" :inline="true">

               <el-form-item label="岗位名称">
                  <el-input style="width:200px" v-model="queryParams.postName" placeholder="请输入岗位名称" @change="onInputPostName"
                     clearable></el-input>
               </el-form-item>

               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>

            <el-row>
               <el-table border @row-click="clickRow" ref="refTable" :data="postArr"
                  @selection-change="handleSelectionChange" height="454">
                  <el-table-column align="center" type="selection" width="55"></el-table-column>
                  <el-table-column width="120" align="center" label="岗位标识" prop="postCode" :show-overflow-tooltip="true" />
                  <el-table-column width="150" align="center" label="岗位名称" prop="postName" :show-overflow-tooltip="true" />
                  <el-table-column align="center" label="所属部门" prop="deptName" :show-overflow-tooltip="true" />
                  <el-table-column width="150" label="状态" align="center" prop="status">
                     <template #default="scope">
                        <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                     </template>
                  </el-table-column>
               </el-table>
            </el-row>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
               v-model:limit="queryParams.pageSize" @pagination="queryParams.deptId ? onClickNode() : getPostList()" />

         </el-col>
      </el-row>

      <template #footer>
         <div class="dialog-footer">
            <el-button type="primary" @click="handleAllocateRoleBindPostDebounceHandler">确 定</el-button>
            <el-button @click="visible = false">取 消</el-button>
         </div>
      </template>

   </el-dialog>
</template>

<script setup name="SelectUser">
import { authUserSelectAll, unallocatedUserList,allocateRoleBindPost } from "@/api/system/role"
import { postListByDept, postListByPostName } from "@/api/system/post"
import { treeselect } from "@/api/system/dept"
import { debounce } from "@/utils/debounce.js";
import { watch } from "vue";

const props = defineProps({
   roleId: {
      type: [Number, String]
   }
});

console.log(props,"<<<=== 父组件传过来的 props");
const { proxy } = getCurrentInstance();
console.log(proxy, "<<<=== proxy");
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const postArr = ref([]);
const visible = ref(false);
const total = ref(0);
const postIdList = ref([]);//多选数组
const deptNameSearch = ref("")
const deptArr = ref([])
const expandedKeys=ref([])

const queryParams = reactive({
   pageNum: 1,
   pageSize: 10,
   deptId: undefined,//部门Id
   postName: null,//岗位名称
});


/**监听关闭弹框时触发事件 */
function onCloseDialog(){
   console.log("关闭了");
   deptNameSearch.value=''
   // 清空当前选中的节点的状态
   console.log(expandedKeys.value,"<<<=== expandedKeys.value---关闭");
   proxy.$refs.deptTreeRef.setCurrentKey(null)
   proxy.$refs.deptTreeRef.setCheckedKeys([])
   handleQuery()

   proxy.$nextTick(()=>{
      expandedKeys.value=recursionFn(deptArr.value)//展开所有的部门树节点
   })

}

/**点击搜索按钮根据部门名称拿分页数据 */
function getPostList() {
   console.log("==========================");
   queryParams.deptId = null
   console.log(queryParams, "<<<=== 点搜索按钮 queryParams");
   postListByPostName(queryParams).then((res) => {
      console.log(res, "<<<=== res 根据岗位名称拿到数据");
      postArr.value = res.rows
      total.value = res.total
   }).catch((error) => {
      console.log(error, "<<<=== error");
   })
}

/**监听部门输入框值的变化 */
watch(deptNameSearch, (newVal, oldVal) => {
   console.log(newVal, "<<<=== newVal");
   console.log(oldVal, "<<<=== oldVal");
   console.log(proxy.$refs.deptTreeRef.filter(newVal), "<<<proxy");
})


/**过滤树形结构-每一个节点都调用这个过滤方法 */
function filterNode(val, data, node) {
   console.log(val, "<<<=== val 过滤条件传过来的关键字");
   // 没有传数据
   if (!val) {
      return true
   }
   // 传了数据
   return data.label.indexOf(val) !== -1
}

/**点击树形节点时触发 */
function onClickNode(e) {
   console.log(e, "<<<=== e  点击树形节点");
   console.log(proxy.$refs.deptTreeRef.getCurrentKey(),"<<<=== proxy.$refs.deptTreeRef.getCurrentKey()");
   console.log(proxy.$refs.deptTreeRef.getCurrentNode(),"<<<=== proxy.$refs.deptTreeRef.getCurrentNode()");
   // 点分页，没点树形结构，没有事件参数e
   if (!e) {
      postListByDept(queryParams).then((res) => {
         console.log(res, "<<<=== 没点部门 点分页 res 点部门拿到岗位数据");
         postArr.value = res.rows
         total.value = res.total
      })
      return
   }
   queryParams.postName = undefined
   queryParams.deptId = e.id
   console.log(queryParams, "<<<=== 点击部门节点时 queryParams");
   postListByDept(queryParams).then((res) => {
      console.log(res, "<<<+++ res 点部门拿到岗位数据");
      postArr.value = res.rows
      total.value = res.total
   })
}

/**点部门树形结构数据的分页 */
// function deptByPagination(){
//    postListByDept(queryParams).then((res) => {
//       console.log(res, "<<<+++ res 点部门拿到岗位数据");
//       postArr.value = res.rows
//       total.value=res.total
//    })
// }

/**拿到部门的树形结构 */
function getDeptTree() {
   treeselect().then((res) => {
      console.log(res, "<<<=== res 拿到部门树形结构");
      deptArr.value = res.data
      console.log(deptArr.value, "<<<=== deptArr");
      console.log(expandedKeys.value,"<<<=== expandedKeys.value---------1");
      recursionFn(deptArr.value)
      expandedKeys.value=recursionFn(deptArr.value)
      console.log(expandedKeys.value,"<<<=== expandedKeys.value-----2");
      console.log(recursionFn(deptArr.value),"<<<=== recursionFn(deptArr.value)");
   }).catch((error) => {
      console.log(error, "<<<=== error");
   })
}

/**输入岗位名称时触发 */
function onInputPostName(val) {
   console.log(val, "<<<=== val 输入岗位名称时触发");

}


/**输入部门名称时触发 */
function onInputDeptName(val) {
   console.log(val, "<<<=== val 输入部门时触发");

}

// 显示弹框
function show() {
   // queryParams.roleId = props.roleId;
   getList();
   visible.value = true;
}
/**选择行 */
function clickRow(row) {
   proxy.$refs["refTable"].toggleRowSelection(row);
}
// 多选框选中数据
function handleSelectionChange(selection) {
   console.log(selection,"<<<=== 多选框 勾选触发");
   postIdList.value = selection.map(item => item.postId);
   console.log(postIdList.value,"<<<=== postIdList 多选拿到的岗位id数组");
}
// 查询列表数据
function getList() {
   // postListByDept(100).then((res) => {
   //    console.log(res, "<<<+++ res 点部门拿到岗位数据");
   //    postArr.value = res.rows
   //    total.value=res.total
   // })
   // postListByDept().then((res)=>{
   //    console.log(res,"<<<=== res 根据部门拿到岗位数据");
   // }).catch((error)=>{
   //    console.log(error,"<<<=== error");
   // })
   // unallocatedUserList(queryParams).then(res => {
   //    postArr.value = res.rows;
   //    total.value = res.total;
   // });
}
/** 搜索按钮操作 */
function handleQuery() {
   queryParams.pageNum = 1;
   console.log(queryParams, "<<<=== queryParams 点搜索按钮");
   // getList();
   getPostList()
}
/** 重置按钮操作 */
function resetQuery() {
   queryParams.postName=null
   //取消部门节点选中状态
   proxy.$refs.deptTreeRef.setCurrentKey(null)
   proxy.$refs.deptTreeRef.setCheckedKeys([])
   handleQuery();
}
const emit = defineEmits(["ok"]);

/** 选择岗位数组绑定给角色 */
/** 提交按钮 */
const handleAllocateRoleBindPostDebounceHandler = debounce(handleAllocateRoleBindPost, 500);
function handleAllocateRoleBindPost() {
   // const roleId = queryParams.roleId;
   const roleId=props.roleId
   console.log(roleId,"<<<=== 点击确定 roleId");
   allocateRoleBindPost({postIdList:postIdList.value,roleId}).then((res)=>{
      console.log(res,"<<<=== res 将岗位绑定到角色上");
      proxy.$modal.msgSuccess(res.msg)
      if(res.code === 200){
         visible.value=false//关闭弹框
         emit("ok")//让父组件监听ok事件，重新请求数据，刷新
      }

   }).catch((error)=>{
      console.log(error,"<<<=== error");
   })
   // const uIds = postIdList.value.join(",");
   // if (uIds == "") {
   //    proxy.$modal.msgError("请选择要分配的用户");
   //    return;
   // }
   // authUserSelectAll({ roleId: roleId, postIdList: uIds }).then(res => {
   //    proxy.$modal.msgSuccess(res.msg);
   //    if (res.code === 200) {
   //       visible.value = false;
   //       emit("ok");
   //    }
   // });
}


/**递归函数 */

function recursionFn(deptArr){
   console.log(deptArr,"<<<=== deptArr");
   let arr=[]
   // [100,101,102]
   // 终止条件，没有找到children就停止遍历
 deptArr.forEach((item)=>{
   if(item.id){
      arr.push(item.id)
   }
   if(item.children){
      arr.push(...recursionFn(item.children))
   }
 })

 return arr

}



defineExpose({
   show,
});

getDeptTree()




</script>

<style scoped lang="scss"></style>
